package cn.zzuisa.controller;


import cn.zzuisa.base.PageRequest;
import cn.zzuisa.base.R;
import cn.zzuisa.config.TokenManager;
import cn.zzuisa.entity.Access;
import cn.zzuisa.entity.Config;
import cn.zzuisa.entity.Member;
import cn.zzuisa.request.DissOtherDo;
import cn.zzuisa.request.LoginMember;
import cn.zzuisa.service.*;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.zzuisa.service.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author frank
 * @since 2019-05-07
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    MemberService memberService;

    @Autowired
    ConfigService configService;

    @Autowired
    AccessService accessService;

    @Autowired
    InvitationService invitationService;

    @Autowired
    DissService dissService;

    @ApiOperation("拉黑传1，取消传0")
    @PutMapping("borw")
    public R<String> borw(@RequestBody DissOtherDo dissOtherDo) {
        if(dissOtherDo == null || dissOtherDo.getDissId() == null
                || dissOtherDo.getStatus() == null || dissOtherDo.getUserId() == null) {
            return  R.error("参数为空");
        }
        Member member = memberService.getById(dissOtherDo.getUserId());
        member.setStatus(dissOtherDo.getStatus());
        dissService.updateById(dissService.getById(dissOtherDo.getDissId()).setStatus(1));
        memberService.updateById(member);
        return R.ok("更新成功");
    }

    @ApiOperation("拉黑传1，取消传0")
    @PutMapping("bor")
    public R<String> bor(@RequestBody DissOtherDo dissOtherDo) {
        if(dissOtherDo == null
                || dissOtherDo.getStatus() == null || dissOtherDo.getUserId() == null) {
            return  R.error("参数为空");
        }
        Member member = memberService.getById(dissOtherDo.getUserId());
        member.setStatus(dissOtherDo.getStatus());
        memberService.updateById(member);
        return R.ok("更新成功");
    }


    //登录
    @PostMapping("/login")
    public R login(@RequestBody LoginMember member, HttpServletRequest request) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", member.getUsername())
                    .eq("password", member.getPassword());
        Member one = memberService.getOne(queryWrapper);
        if(one == null) {
            return R.error("账号或密码错误");
        }
        if(one.getStatus() != 0) {
            return R.error("账号被限制");
        }
        String token = UUID.randomUUID().toString();
        TokenManager.put(token,one.getId());
        HashMap<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("member",one);
        return R.ok(map);
    }
    // 注册账号
    @PostMapping("/join")
    public R join(@RequestBody Member member) {
        if(member.getName() == null) {
            return R.error("昵称不能为空");
        }
        if(member.getUsername() == null) {
            return R.error("账号不能为空");
        }
        if(member.getPassword() == null) {
            return R.error("密码不能为空");
        }
        Member one = memberService.getOne(new QueryWrapper<Member>().eq("username", member.getUsername()));
        if(one != null) {
            return R.error("用户名已存在");
        }
        if(StringUtils.isEmpty(member.getHeadImg())){
            member.setHeadImg("https://i7.3conline.com/images/upload/upc/face/29/47/75/76/29477576_70x70");
        }
        memberService.save(member);
        return R.ok(member);
    }
    //修改密码
    @PutMapping("/password")
    public R<String> updatePassword(String password, HttpServletRequest request) {
        Long id = TokenManager.get(request.getHeader("token"));
        Member member = memberService.getById(id);
        member.setPassword(password);
        memberService.updateById(member);
        return R.error("修改成功");
    }
    @ApiOperation("userId不传就是查个人")
    @GetMapping("/info")
    public R<Map<String,Object>> selfInfo(HttpServletRequest request,Long userId) {
        String s = request.getHeader("token");
        Long loginId = null;
        if(s!=null) {
            loginId = TokenManager.get(s);
        }
        loginId = 3L;
        Member byId = memberService.getById(loginId);
        userId = userId == null ? loginId : userId;
        if(userId != null) {
            accessService.save(
                    new Access().setMemberId(userId)
                            .setAccessId(loginId)
                            .setAccessImg(byId.getHeadImg())
                            .setAccessName(byId.getName())
                            .setAccessTime(LocalDateTime.now())
            );
        }
        Map<String,Object> token = memberService.getMap(new QueryWrapper<Member>().eq("id",userId));
        Config one = configService.getOne(new QueryWrapper<Config>().eq("config_name", String.valueOf(token.get("level"))));
        token.put("levelName",one == null ? "无名小卒" : one.getConfigValue());
        return R.ok(token);
    }


    // 修改个人信息 头像 邮箱 电话 性别 昵称
    @PutMapping("/new")
    public R update(@RequestBody Member member,HttpServletRequest request) {
        Long userId = TokenManager.get(request.getHeader("token"));
        Member member1 = memberService.getById(userId);
        member1.setHeadImg(member.getHeadImg());
        member1.setMail(member.getMail());
        member1.setPhone(member.getPhone());
        member1.setSex(member.getSex());
        member1.setName(member.getName());
        member1.setAddress(member.getAddress());
        member1.setIntroduce(member.getIntroduce());
        member1.setSignature(member.getSignature());
        memberService.updateById(member1);
        return R.ok(member1);
    }

    // 退出登錄
    @GetMapping("/out")
    public R<String> logout(HttpServletRequest request) {
        TokenManager.rm(request.getHeader("token"));
        return R.ok("退出登路");
    }

    @GetMapping("/page")
    public R page(PageRequest page, String name) {
        Page page1 = new Page(page.getCurrent(),page.getSize());
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        if(name != null) {
            queryWrapper.like("name",name).or().like("username",name);
        }
        IPage<Member> page2 = memberService.page(page1, queryWrapper);
       return R.ok(page2);
    }

    @ApiOperation("版主 副版主")
    @GetMapping("/zhu")
    public R<List<Map<String,Object>>> q() {
        List<Map<String,Object>> list = memberService.listByDescInvitationCount();
        if(list != null && list.size() > 0) {
            list.stream().forEach(item -> {
                Long id = (Long) item.get("id");
                Member byId = memberService.getById(id);
                item.put("info",byId);
            });
        }
        return R.ok(list);
    }


}
